//
//  KABCosplayActivityVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/6/19.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABCosplayActivityVC.h"
#import "KABCosActiviyCCell.h"
#import "KABModel.h"
#import <MJRefresh.h>
#import "XDAFNetworking.h"
#import "ApiManager.h"
#import "MBProgressHUD+XDPrompt.h"
#import "GlobalHeader.h"
#import <UIScrollView+EmptyDataSet.h>
#import "KABMallTitleView.h"
#import "ThemeManager.h"
#import "KABCosplayDetailVC.h"

@interface KABCosplayActivityVC ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource, KABMallTitleViewDelegate, KABCosActiviyCCellDelegate>

@property (weak,   nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;
@property (strong, nonatomic) KABMallTitleView *mallTitleView;

@property (nonatomic, strong) KABCosActivityModel *activityModel;

@end

static NSString *const kReuseCellId = @"KABCosActiviyCCell";
static NSInteger const kRequestCosplayListSize = 20;

@implementation KABCosplayActivityVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.mallTitleView endEditing:YES];
}

- (void)initNavigationBar {
    self.navigationItem.title = self.activityTitle;
    [self.mallTitleView setTextFieldPlaceholder:self.activityTitle];
    if (self.viewType == KABCosplayActivityVCTypeSearch) {
        [self.mallTitleView setTextFieldText:self.seachInitText];
    }
    self.navigationItem.titleView = self.mallTitleView;
    
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)initSubViews {
    UINib *cellNib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:kReuseCellId];
    //    UINib *cRViewNib = [UINib nibWithNibName:kReuseHeaderId bundle:nil];
    //    [self.collectionView registerNib:cRViewNib forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kReuseHeaderId];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.emptyDataSetDelegate = self;
    self.collectionView.emptyDataSetSource = self;
    
    // 下拉刷新
    self.collectionView.mj_header = self.mj_header;
    self.collectionView.mj_footer = self.mj_footer;
    // 请求数据
    [self.collectionView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"没有参赛作品喔" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.activityModel.coser_list.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    KABCosActiviyCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.item < self.activityModel.coser_list.count) {
        [cell configViewWithCosActItem:self.activityModel.coser_list[indexPath.item]];
    }
    cell.delegate = self;
    return cell;
}

//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
//    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
//        KABMallHeaderCRView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kReuseHeaderId forIndexPath:indexPath];
//        header.delegate = self;
//        return header;
//    }
//
//    return nil;
//}

#pragma mark - <UICollectionViewDelegateFlowLayout>
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
//    CGFloat width = CGRectGetWidth(self.view.bounds);
//    CGFloat height = width * 244.0 / 375.0;
//    return CGSizeMake(width, height);
//}

//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
//    return CGSizeMake(CGRectGetWidth(self.view.bounds), 6.0);
//}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width = (CGRectGetWidth(self.view.bounds) - 2*6 - 6) / 2.0;
    CGFloat height = width;
    return CGSizeMake(width, height);
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    KABCosActivityItem *item = nil;
    if (indexPath.item < self.activityModel.coser_list.count) {
        item = self.activityModel.coser_list[indexPath.item];
    }
    KABCosplayDetailVC *detailVC = [[KABCosplayDetailVC alloc] init];
    detailVC.cosplay_id = item.cosplay_id;
    [self showViewController:detailVC sender:nil];
}

//- (void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
//    if ([elementKind isEqualToString:UICollectionElementKindSectionHeader]) {
//        KABMallHeaderCRView *headerView = (KABMallHeaderCRView *)view;
//        [headerView bannerViewStartScroll];
//    }
//}
//
//- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(UICollectionReusableView *)view forElementOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
//    if ([elementKind isEqualToString:UICollectionElementKindSectionHeader]) {
//        KABMallHeaderCRView *headerView = (KABMallHeaderCRView *)view;
//        [headerView bannerViewStopScroll];
//    }
//}

#pragma mark - KABCosActiviyCCellDelegate
- (void)kABCosActiviyCCell:(KABCosActiviyCCell *)cell voteBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    KABCosActivityItem *item = self.activityModel.coser_list[indexPath.row];
    if (item.is_voted) {
        return;
    }
    
    [self requestCosplayVoteWithCosId:item.cosplay_id success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
        NSLog(@"请求投票返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            item.is_voted = YES;
            item.ballot++;
            [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    }];
}

#pragma mark - KABMallTitleViewDelegate
- (void)kABMallTitleView:(KABMallTitleView *)view searchBtnTapped:(UIButton *)btn {
    if (self.viewType == KABCosplayActivityVCTypeList) {
        KABCosplayActivityVC *vc = [[KABCosplayActivityVC alloc] init];
        vc.activityId = self.activityId;
        vc.activityTitle = @"请输入用户昵称";
        vc.viewType = KABCosplayActivityVCTypeSearch;
        vc.seachInitText = view.inputText;
        [self showViewController:vc sender:nil];
        [self.mallTitleView setTextFieldText:nil];
    } else {
        [self requestActivityWithHeader:YES activityId:self.activityId keyword:view.inputText];
    }
}
- (void)kABMallTitleView:(KABMallTitleView *)view textFieldChanged:(UITextField *)textField {
    if (self.viewType == KABCosplayActivityVCTypeSearch) {
        [self requestActivityWithHeader:YES activityId:self.activityId keyword:view.inputText];
    }
}

#pragma mark - event response

#pragma mark - private methods
- (void)refreshWholeView {
    // 尾部加载更多的显示
    if (self.activityModel.totalLoad) {
        [self.collectionView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.collectionView.mj_footer resetNoMoreData];
    }
    
    NSString *placeHolder = (self.viewType == KABCosplayActivityVCTypeList) ? self.activityModel.activity_name : @"请输入用户昵称";
    [self.mallTitleView setTextFieldPlaceholder:placeHolder];
    [self.collectionView reloadData];
}

- (void)collectionViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.collectionView.mj_header endRefreshing];
    } else {
        [self.collectionView.mj_footer endRefreshing];
    }
}

- (void)collectionViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    NSString * keyword = (self.viewType == KABCosplayActivityVCTypeSearch) ? self.mallTitleView.inputText : nil;
    [self requestActivityWithHeader:isHeader activityId:self.activityId keyword:keyword];
}

- (KABCosActivityModel *)activityVoteListWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.activityModel;
    }
    
    KABCosActivityModel *temp = [KABCosActivityModel yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
    if (!temp) {
        return self.activityModel;
    }
    
    if (AddMore && self.activityModel) {
        [self.activityModel addMoreWithData:temp];
    } else {
        self.activityModel = temp;
    }
    return self.activityModel;
}

#pragma mark - network request
- (void)requestActivityWithHeader:(BOOL)isHeader activityId:(NSInteger)activityId keyword:(NSString *)keyword {
    NSInteger startIndex = isHeader ? 0 : self.activityModel.coser_list.count;
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@(startIndex) forKey:@"index"];
    [pars setObject:@(kRequestCosplayListSize) forKey:@"size"];
    [pars setObject:@(activityId) forKey:@"activity_id"];
    if ([KABModel sharedInstance].isLogin) {
        [pars setObject:@([KABModel sharedInstance].userInfo.uid) forKey:@"user_id"];
        [pars setObject:[KABModel sharedInstance].userInfo.access_token forKey:@"access_token"];
    }
    if (keyword) {
        [pars setObject:keyword forKey:@"keyword"];
    }
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiCosplayActivity] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求投票列表返回：%@", responseObject);
        [self collectionViewEndRefresh:isHeader];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [self activityVoteListWithDictionary:responseObject isAddMore:!isHeader];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求商品列表失败：%@", error);
        [self collectionViewEndRefresh:isHeader];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestCosplayVoteWithCosId:(NSInteger)cosplay_id success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success {
    // 投票必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    // 关注请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"cosplay_id" : @(cosplay_id)};
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiCosplayVote] parameters:pars progress:nil success:success failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求投票失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters
- (KABMallTitleView *)mallTitleView {
    if (!_mallTitleView) {
        _mallTitleView = [[KABMallTitleView alloc] init];
        _mallTitleView.bgColor = [[ThemeManager sharedManager] themeColorWithName:ThemeManagerMallSeaBgColor];
        _mallTitleView.textColor = [[ThemeManager sharedManager] themeColorWithName:ThemeManagerMallSeaTextColor];
        _mallTitleView.placeholderColor = [[ThemeManager sharedManager] themeColorWithName:ThemeManagerMallSeaPlaceholderColor];
        _mallTitleView.textFieldTintColor = [[ThemeManager sharedManager] themeColorWithName:ThemeManagerMallSeaTextFieldTintColor];
        _mallTitleView.delegate = self;
    }
    return _mallTitleView;
}

- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(collectionViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(collectionViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}

@end
